package com.xmut.mall.ware.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {

//    @Autowired
//    private HttpServletRequest request;

    @Override
    public void apply(RequestTemplate requestTemplate) {
//        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = requestAttributes.getRequest();
//
//        requestTemplate.header("User-Agent",request.getHeader("User-Agent"));
//        log.info("追加User-Agent",request.getHeader("User-Agent"));
//        if (request.getAttribute("newAccessToken") == null){
//            requestTemplate.header("accessToken",request.getHeader("accessToken"));
//            requestTemplate.header("refreshToken",request.getHeader("refreshToken"));
//        }else if(request.getAttribute("newAccessToken") != null) {
//            requestTemplate.header("accessToken",request.getAttribute("newAccessToken").toString());
//            requestTemplate.header("refreshToken",request.getAttribute("newRefreshToken").toString());
//        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest(); // 老的请求
            if (request != null) {
                log.info("UserAgent:" + request.getHeader("User-Agent"));
                requestTemplate.header("User-Agent", request.getHeader("User-Agent"));
                if (request.getAttribute("newAccessToken") == null) {
                    requestTemplate.header("accessToken", request.getHeader("accessToken"));
                    requestTemplate.header("refreshToken", request.getHeader("refreshToken"));
                } else if (request.getAttribute("newAccessToken") != null) {
                    requestTemplate.header("accessToken", request.getAttribute("newAccessToken").toString());
                    requestTemplate.header("refreshToken", request.getAttribute("newRefreshToken").toString());
                }
                // 同步请求头数据,Cookie
                String cookie = request.getHeader("Cookie");
                // 给新请求同步老请求的cookie
                requestTemplate.header("Cookie", cookie);
            }
        }
    }
}
